package com.wanghang89.gmail.util.db;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.PreparedStatementCallback;

public class AddBatchPreparedStatementCallback implements PreparedStatementCallback<Boolean> {
	
	private Object[][] params;
	
	private final static Logger LOGGER = Logger.getLogger(AddBatchPreparedStatementCallback.class);
	
	public AddBatchPreparedStatementCallback( Object[][] params)
	{
		this.params = params;
	}
	
	@Override
	public Boolean doInPreparedStatement(PreparedStatement pstmt)
			throws SQLException, DataAccessException {
		int olength = params.length;
		LOGGER.debug("olength:"+olength);
		for (int i = 0; i < olength; i++) {
			Object[] fields = params[i];
			int flength = fields.length;
			LOGGER.debug("flength:"+flength);
			for (int j = 0; j < flength; j++) {
				pstmt.setObject(j + 1, params[i][j]);
			}
			pstmt.addBatch();
		}
		pstmt.executeBatch();
		if (LOGGER.isDebugEnabled()) {
			ResultSet rs = null;
			rs = pstmt.getGeneratedKeys();
			while (rs.next()) {
				long id = rs.getLong(1);
				LOGGER.debug("method add,id:" + id);
			}
		}
		params = null;
		return true;
	}

}
